package com.comac.print.component.app.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.comac.mom.simpleintegration.oss.OSSComponent;
import com.comac.mom.simpleintegration.oss.OssUtil;
import com.itextpdf.text.DocumentException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;


/**
 * 文件处理
 */
@Component
@Slf4j
public class FileOperateUtil {

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.bucketName}")
    private String bucketName;


    @Autowired
    OSSComponent ossComponent;

    @Autowired
    ResourceLoader resourceLoader;
    @Resource
    private Html2PdfUtils html2PdfUtils;


    final String IMAGE_HEAD="data:image/png;base64,";
    /**
     * 目录
     */
    private static final String PATH = "MOM2/FO-CENTER/FO-EXECUTE/";

    /**
     * 文件上传
     */
    public String uploadFoFile(String fileName, InputStream inputStream) {
        log.info("FoFileOperateUtil upload fileName is {}");
        try {
            return ossComponent.upload(fileName, PATH, inputStream);
        } catch (Exception e) {
            log.error("FoFileOperateUtil is error!", e);
        }
        return null;
    }


    /**
     * 文件上传
     *
     * @param fileName 文件名(需保持唯一，防止覆盖)
     * @param contents 文件内容
     */
    public String uploadFoFileWithContents(String fileName, String contents) {
        log.info("FoFileOperateUtil upload fileName is {}, contents is {}", fileName, contents);
        byte[] bytes = contents.getBytes(StandardCharsets.UTF_8);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        try {
            OssUtil ossUtil = OssUtil.create(endpoint, accessKeyId, accessKeySecret, bucketName);
            return ossUtil.uploadOss(fileName, PATH, byteArrayInputStream);
        } catch (Exception e) {
            log.error("FoFileOperateUtil is error!", e);
        }
        return null;
    }

    /**
     * 文件上传返回oss地址
     */
    public String uploadFoFileToOss(String fileName, InputStream inputStream) {
        log.info("FoFileOperateUtil upload fileName is {}");
        try {
            return ossComponent.upload(fileName, PATH, inputStream);
        } catch (Exception e) {
            log.error("FoFileOperateUtil is error!", e);
        }
        return null;
    }


    /**
     * 导出HTML到pdf文件
     * @param data
     * @param tmpName 模板名
     * @return
     * @throws FileNotFoundException
     * @throws DocumentException
     */
    public String exportToFile(Object data,String tmpName) throws Exception {
        String htmlData= PdfHtmlUtils.getContent(data,tmpName+".html");

        String fileName = tmpName+System.currentTimeMillis()+".pdf";
//        InputStream inputStream = new ByteArrayInputStream(ItextPdfUtils.generateHorizontal(htmlData,"","").toByteArray());
        InputStream inputStream = new ByteArrayInputStream(html2PdfUtils.convertWithOnlyOffice(htmlData,"", ""));
        String url = uploadFoFileToOss(fileName, inputStream);
        return url;
    }

    /**
     * 根据url获取输入流
     *
     * @param strUrl
     * @return
     */
    public static InputStream getInputStreamByUrl(String strUrl) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20 * 1000);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(), output);
            return new ByteArrayInputStream(output.toByteArray());
        } catch (Exception e) {
            log.error("getInputStreamByUrl err ", e);
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
                log.error("getInputStreamByUrl getInputStreamByUrl ", e);
            }
        }
        return null;
    }
    /**
     * 根据Ossurl获取输入流
     *
     * @param ossUrl
     * @return
     */
    public  InputStream  getInputStreamByOssUrl(String ossUrl) {
        try {
            URL url = new URL(ossUrl);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            BufferedInputStream input = null;
            String fileFolder = url.getPath().substring(1);
            log.info("fileFolder : {}",fileFolder);

            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            OSSObject ossObject = ossClient.getObject(bucketName, fileFolder);
            try {
                input = new BufferedInputStream(ossObject.getObjectContent());
                IOUtils.copy(input, output);
                return  new ByteArrayInputStream(output.toByteArray());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                ossClient.shutdown();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) throws Exception {
        String test = "test";
        FileOperateUtil fileOperateUtil = new FileOperateUtil();
        String s = fileOperateUtil.uploadFoFile("1323432", new ByteArrayInputStream(test.getBytes()));
        System.out.println(s);

//        String fileName = UUID.randomUUID().toString().toUpperCase().replace("-", "") + ".xmind";
//        OssUtil ossUtil = OssUtil.create(fileOperateUtil.endpoint,fileOperateUtil.accessKeyId, fileOperateUtil.accessKeySecret, fileOperateUtil.bucketName);
//        File file = new File("E:\\项目\\商飞二期\\商飞2期需求.xmind");
//        String s = ossUtil.upload(file.getName(), PATH + "123456", new FileInputStream(file));
//        System.out.println(s);
    }
    /**
     * 根据图片名获取图片base64字符串
     * @param imageName
     * @return
     */
    public String getImageBase64(String imageName) {
        InputStream is=null;
        try {
            ClassPathResource classPathResource =new ClassPathResource("tmp/img/" +imageName);
            is = classPathResource.getInputStream();
            return  IMAGE_HEAD+ ImageUtils.image2Base64ByInput(is);
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}

